#!/bin/bash

# 网络接口驱动查询脚本
# 通过命令参数传入网卡名称，或自动检测网卡并供用户选择
# 自动分类显示为设备类型分类（Ethernet、有线网卡、无线网卡、桥接设备、隧道设备、虚拟设备、本地主机环回）

# 打印分类后的网卡列表
list_interfaces() {
    echo "可用网卡列表："

    echo "[本地主机环回接口]"
    for f in /sys/class/net/*; do
        dev=$(basename "$f")
        if [ "$dev" == "lo" ]; then
            echo "- $dev"
        fi
    done

    echo "[有线网卡 (Ethernet)]"
    for f in /sys/class/net/*; do
        dev=$(basename "$f")
        driver=$(ethtool -i "$dev" 2>/dev/null | awk -F': ' '/driver/ {print $2}')
        if [[ "$driver" =~ ^(r8169|e1000|igb|ixgbe|atlantic|tg3)$ ]]; then
            echo "- $dev"
        fi
    done

    echo "[无线网卡 (Wi-Fi)]"
    for f in /sys/class/net/*; do
        dev=$(basename "$f")
        driver=$(ethtool -i "$dev" 2>/dev/null | awk -F': ' '/driver/ {print $2}')
        if [[ "$driver" =~ ^(wl|ath|iwlwifi|rtl|mt7601u|rt2800usb)$ ]]; then
            echo "- $dev"
        fi
    done

    echo "[桥接设备 (Bridge)]"
    for f in /sys/class/net/*; do
        dev=$(basename "$f")
        if [ -d "/sys/class/net/$dev/bridge" ]; then
            echo "- $dev"
        fi
    done

    echo "[隧道设备 (Tunnel)]"
    for f in /sys/class/net/*; do
        dev=$(basename "$f")
        if [[ "$dev" == tun* ]] || [[ "$dev" == zt* ]]; then
            echo "- $dev"
        fi
    done

    echo "[虚拟设备]"
    for f in /sys/class/net/*; do
        dev=$(basename "$f")
        if [[ "$dev" == docker* ]] || [[ "$dev" == virbr* ]] || [[ "$dev" == vmnet* ]] || [[ "$dev" == veth* ]]; then
            echo "- $dev"
        fi
    done

    echo
}

# 获取网卡驱动信息
get_driver_info() {
    local dev="$1"
    if [ -d "/sys/class/net/$dev" ]; then
        driver=$(basename "$(readlink "/sys/class/net/$dev/device/driver/module" 2>/dev/null)" 2>/dev/null)
        driver_path=$(readlink -f "/sys/class/net/$dev/device/driver" 2>/dev/null)
        module_name=$(basename "$(readlink "/sys/class/net/$dev/device/driver/module" 2>/dev/null)" 2>/dev/null)
        if [ -z "$driver" ]; then
            driver=$(ethtool -i "$dev" 2>/dev/null | awk -F': ' '/driver/ {print $2}')
        fi
        if [ -z "$driver" ]; then
            driver="Unknown"
        fi
        echo "网卡: $dev"
        echo "驱动: $driver"
        if [ -n "$module_name" ]; then
            echo "模块名称: $module_name"
            echo "驱动路径: $driver_path"
        fi
    else
        echo "错误：网卡 '$dev' 不存在！"
        exit 1
    fi
}

# 主程序入口
if [ $# -ge 1 ]; then
    get_driver_info "$1"
else
    list_interfaces
    read -p "请输入要查询驱动的网卡名称: " dev_name
    get_driver_info "$dev_name"
fi
